package com.tangsm.spring.boot.filter.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Filter过滤测试接口
 *
 * @author tangsm
 */
@RestController
@RequestMapping("/api")
public class FilterController {

    private static final Logger log = LoggerFactory.getLogger(FilterController.class);

    private static final List<UserInfo> userList = new ArrayList<>();

    static {
        for (int i = 0; i < 10; i++) {
            UserInfo userInfo = new UserInfo();
            userInfo.setLoginId(String.valueOf(1 + i));
            userInfo.setUserName("张三" + i);
            userInfo.setAge(20 + i);
            userList.add(userInfo);
        }
    }

    @GetMapping("/v1/{name}")
    public String v1(@PathVariable("name") String name) {
        return "hello " + name + " v1";
    }

    @PostMapping("/v2")
    public String v2(@RequestBody LoginInfo loginInfo) {
        return "hello " + loginInfo.getUserName() + ", password: " + loginInfo.getPassword();
    }

    @PostMapping("/v3")
    public String v3(@RequestBody UserInfo userInfo) {
        log.info("v3请求参数：{}", userInfo.toString());
        String loginId = userInfo.getLoginId();
        Optional<UserInfo> first = userList.stream().filter(user -> user.getLoginId().equals(loginId)).findFirst();
        userInfo = first.orElse(userInfo);
        log.info("响应对象：{}", userInfo);
        return "loginId: " + userInfo.getLoginId() + ", userName: " + userInfo.getUserName() + ", age: " + userInfo.getAge();
    }
}

/**
 * 登录信息
 *
 * @author tangsm
 */
class LoginInfo {
    private String userName;
    private String password;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

/**
 * 用户信息
 *
 * @author tangsm
 */
class UserInfo {
    private String loginId;
    private String userName;
    private Integer age;

    public String getLoginId() {
        return loginId;
    }

    public void setLoginId(String loginId) {
        this.loginId = loginId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "UserInfo{" +
                "loginId='" + loginId + '\'' +
                ", userName='" + userName + '\'' +
                ", age=" + age +
                '}';
    }
}
